<script setup>
import { ref, onMounted } from 'vue';
import { ElTable, ElDialog, ElForm, ElFormItem, ElInput, ElSelect, ElButton, ElMessage, ElPagination } from 'element-plus';
import { getProducts, addProduct, updateProduct, deleteProduct } from '@/api/product';
import qs from "qs";

const loading = ref(false);
const products = ref([]);
const total = ref(0);
const queryParams = ref({
  page: 1,
  pageSize: 10,
  keyword: ''
});

const dialogForm = ref({
  id: null,
  name: '',
  price: '',
  description: '',
  imageUrl: '',
  status: null
});

const dialogVisible = ref(false);
const isEdit = ref(false);

const fetchProducts = async () => {
  loading.value = true;
  try {
    const response = await getProducts(queryParams.value);

    // ✅ 关键修正！根据你的 console.log，response.data 就是那个数组！
    products.value = response.data;

    // ✅ 分页修正：后端没有返回 total 总数，我们暂时用当前列表的长度
    // 这样分页器至少不会显示一个巨大的数字。
    // (要实现真正的分页，需要后端改造接口，返回一个包含 list 和 total 的对象)
    total.value = response.data.length;
    // 如果后端以后改造了，再改回 total.value = response.data.total;

  } catch (error) {
    console.error("捕获到错误:", error);
    ElMessage.error('获取商品列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

onMounted(fetchProducts);

const handleAdd = () => {
  dialogForm.value = { id: null, name: '', price: '', description: '', imageUrl: '', status: null };
  isEdit.value = false;
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  dialogForm.value = { ...row };
  isEdit.value = true;
  dialogVisible.value = true;
};

const handleSubmit = async () => {
  try {
    if (isEdit.value) {
      await updateProduct(dialogForm.value);
      ElMessage.success('修改成功');
    } else {
      await addProduct({
        name: dialogForm.value.name,
        price: dialogForm.value.price,
        description: dialogForm.value.description,
        imageUrl: dialogForm.value.imageUrl,
        status: dialogForm.value.status
      });
      ElMessage.success('添加成功');
    }
    dialogVisible.value = false;
    fetchProducts();
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

const handleDelete = async (id) => {
  await deleteProduct(id);
  ElMessage.success('删除成功');
  fetchProducts();
};

const handlePageChange = (page) => {
  queryParams.value.page = page;
  fetchProducts();
};
</script>

<template>
  <div class="product-list-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>商品管理</h3>
          <el-button type="primary" @click="handleAdd" style="margin-left: 20px;">
            添加商品
          </el-button>
        </div>
      </template>

      <el-form :inline="true" @submit.native.prevent>
        <el-form-item label="商品名">
          <el-input v-model="queryParams.keyword" placeholder="请输入商品名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchProducts">查询</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="products" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="商品名" />
        <el-table-column prop="price" label="价格" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="queryParams.pageSize"
          @current-change="handlePageChange"
      />
    </el-card>

    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑商品' : '添加商品'"
    >
      <el-form>
        <el-form-item label="商品名">
          <el-input v-model="dialogForm.name" placeholder="请输入商品名" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="dialogForm.price" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="dialogForm.description" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="dialogForm.status" placeholder="请选择状态">
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.product-list-container {
  padding: 20px;
}
</style>